package com.offices.subscribe.utils;


import com.alibaba.fastjson.JSONObject;
import com.offices.subscribe.dto.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
public class AccessTokenUtil {

    @Autowired
    private AccessToken accessToken;

    /**
     *@ClassName AccessTokenUtil
     *Description: 请求微信API获得token
     *
     *@Return:void
     *@Author:作者
     *@Date:2020/04/28 17:04
     */
    private void getToken(){
//        添加参数
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("grant_type", accessToken.getGrant_type());
        paramsMap.put("appid", accessToken.getAppid());
        paramsMap.put("secret", accessToken.getSecret());
        //            发出token验证请求
        JSONObject responesJson = HttpClientUtil.doRequest(accessToken.getUrl(), HttpRequestMethod.GET, paramsMap);
//                更新token
        accessToken.setAccess_token(responesJson.getString("access_token"));
//                 更新过期时间
        accessToken.setExpires_in(responesJson.getString("expires_in"));
    }

    /**
     *@ClassName AccessTokenUtil
     *Description: 向外暴露获得token方法
     *
     *@Return:java.lang.String
     *@Author:作者
     *@Date:2020/04/28 17:05
     */
    public String getAccessToken(){
//        如果token为空或者过期就重新获得token
        if (accessToken.getAccess_token() == null || accessToken.isExpires()) {
            this.getToken();
        }
        System.out.println(accessToken.getAccess_token());
//        返回token
        return accessToken.getAccess_token();
    }

}
